<template>
  <div class="book-list">
    <el-form :inline="true" class="demo-form-inline">
  <!-- 图书名称 -->
<el-form-item label="图书名称">
  <el-input v-model="searchForm.bookName" placeholder="请输入图书名称" style="width: 160px" :disabled="isDisabled('bookName') "/>
</el-form-item>

<!-- 作者 -->
<el-form-item label="作者">
  <el-input v-model="searchForm.author" placeholder="请输入作者" style="width: 160px" :disabled="isDisabled('author') "/>
</el-form-item>

<!-- ISBN号 -->
<el-form-item label="ISBN号">
  <el-input v-model="searchForm.isbn" placeholder="请输入ISBN号" style="width: 160px" :disabled="isDisabled('isbn')"/>
</el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form> 

    <!-- 图书列表 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="index" label="序号" width="50">
        <template #default="scope">
         {{ scope.$index + 1 }}
      </template>
      </el-table-column>
      <el-table-column prop="bookName" label="图书名称"></el-table-column>
      <!--<el-table-column prop="bookIntro" label="图书简介"></el-table-column>-->
      <el-table-column prop="author" label="作者"></el-table-column>
      <el-table-column prop="publisher" label="出版社"></el-table-column>
      <el-table-column prop="isbn" label="ISBN号"></el-table-column>
      <el-table-column label="关联分类">
        <template #default="scope">
          {{ getCategoryLabel(scope.row.relatedCategory) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="是否上架"></el-table-column>
      <el-table-column prop="price" label="价格">
        <template #default="scope">
          ￥{{ Number(scope.row.price).toFixed(2)}}
        </template>
      </el-table-column>
      <el-table-column prop="icon" label="图标">
        <template #default="scope">
          <img :src="scope.row.icon" alt="Icon" style="width: 50px; height: 50px;">
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存"></el-table-column>
      <el-table-column label="操作" width="190">
        <template #default="scope">
            <div style="display: flex; align-items: center;">
      <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
      <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      <el-button 
        size="small"
        :type="scope.row.status === '上架' ? 'danger' : 'success'"
        @click="toggleStatus(scope.$index, scope.row)">
        {{ scope.row.status === '上架' ? '下架' : '上架' }}
      </el-button>
    </div>
        </template>
      </el-table-column>
    </el-table>
  </div>

<!-- 图书修改对话框 -->
<el-dialog v-model="editDialogVisible" title="修改图书信息" width="600px">
  <el-form :model="editForm" label-width="100px" ref="editFormRef">
    <!-- 图书名称 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item label="图书名称">
          <el-input v-model="editForm.bookName" />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 作者 + 出版社 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="作者">
          <el-input v-model="editForm.author" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="出版社">
          <el-input v-model="editForm.publisher" />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- ISBN + 是否上架 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="ISBN号">
          <el-input v-model="editForm.isbn" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="库存">
          <el-input v-model="editForm.stock" />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 关联分类 和价格-->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="关联分类">
          <el-select v-model="editForm.relatedCategory" placeholder="请选择分类" style="width: 100%">
            <el-option
              v-for="category in categoryOptions"
              :key="category.value"
              :label="category.label"
              :value="category.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item label="价格">
          <el-input v-model="editForm.price"   />
        </el-form-item>
      </el-col>
    </el-row>
    </el-row>

    <!-- 是否推荐 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="是否推荐">
          <el-radio-group v-model="editForm.isRecommended">
            <el-radio :label="1">不推荐</el-radio>
            <el-radio :label="2">推荐</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>

  <!-- 是否轮播 -->
  <el-row :gutter="20">
    <el-col :span="12">
      <el-form-item label="是否轮播">
        <el-radio-group v-model="editForm.isBanner">
          <el-radio :label="1">不轮播</el-radio>
          <el-radio :label="2">轮播</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-col>
  </el-row>
    
    <!-- 图书简介 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item label="图书简介">
          <el-input v-model="editForm.bookIntro" type="textarea" :rows="3" />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 封面图上传 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item label="封面图">
          <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            :http-request="customUpload"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            >
            <img v-if="editForm.icon" :src="editForm.icon" class="avatar" title="点击修改图片">
            <el-icon v-else><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

  <template #footer>
    <div class="dialog-footer">
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitEditForm">保存</el-button>
    </div>
  </template>
</el-dialog>

<!-- 分页 -->
     <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentPageChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, prev, pager, next"
      :total="total">
    </el-pagination> 
</template>

<script setup>
import { ref ,reactive,onMounted,computed,watch} from 'vue';
import{  ElMessage,ElMessageBox } from 'element-plus'
import axios from 'axios'
axios.defaults.baseURL = "http://localhost:8080"
const uploadRef = ref(); 

const categoryOptions = ref([]) 
 
const currentPage = ref(1);
const pageSize = ref(6);
const total = ref(0);
const tableData = ref([]); // 当前页数据
const allBookData = ref([]);

// 分页方法
const handleCurrentPageChange = async (val) => {
  currentPage.value = val;
  await getBookList(); // 切换页面后重新获取数据
};

const handleSizeChange = async (val) => {
  pageSize.value = val;
  await getBookList(); // 切换每页显示数量后重新获取数据
};

// 查询条件
const searchForm = ref({
   bookName: '',
   author: '',
   isbn: ''
});

// 是否已有输入
const hasInput = computed(() => {
  const form = searchForm.value
  if (!form) return false
  return form.bookName !== '' || form.author !== '' || form.isbn !== ''
})

const isDisabled = (field) => {
  const form = searchForm.value
  if (!form) return false

  const { bookName, author, isbn } = form

  switch (field) {
    case 'bookName':
      return hasInput.value && (author !== '' || isbn !== '')
    case 'author':
      return hasInput.value && (bookName !== '' || isbn !== '')
    case 'isbn':
      return hasInput.value && (bookName !== '' || author !== '')
    default:
      return false
  }
}

// 查询图书
const handleSearch = async() => {
  const { bookName, author, isbn } = searchForm.value;

  // 判断所有条件是否为空
  if (!bookName && !author && !isbn) {
    ElMessage.info('未输入查询条件，正在加载全部图书');
    await getBookList(); // 加载全部数据
    return;
  }

  let params = {
    page: currentPage.value,
    pageSize: pageSize.value
  };

  const token = sessionStorage.getItem('token');
  // 根据不同的查询条件构建参数
  if (bookName) {
    params.title = bookName;
    const res = await axios.get('/admin/books/searchTitle', { params,
      headers: {
          Authorization: `${token}`
        }
     });
    handleSearchResponse(res);
  } else if (author) {
    params.author = author;
    const res = await axios.get('/admin/books/searchAuthor', { params,
      headers: {
        Authorization: `${token}`
      }
     });
    handleSearchResponse(res);
  } else if (isbn) {
    params.Isbn = isbn;
    const res = await axios.get('/admin/books/searchIsbn', { params,
      headers: {
        Authorization: `${token}`
      }
     });
    handleSearchResponse(res);
  }
};

// 处理查询响应的通用方法
const handleSearchResponse = (res) => {
  if (res.data.code === 0 && res.data.data) {
    const data = res.data.data;
    const records = data.records || [];

    tableData.value = records.map((book, index) => ({
      index: (data.current - 1) * data.size + index + 1,
      bookName: book.title,
      bookIntro: book.description,
      author: book.author,
      publisher: book.publisher,
      isbn: book.isbn,
      relatedCategory: book.categoryId, 
      status: book.status === 1 ? '上架' : '下架',
      icon: book.coverUrl?.startsWith('http') 
            ? book.coverUrl 
            : `http://localhost:8080${book.coverUrl}`,
      stock: book.stock,
      price: book.price,
      bookId: book.bookId,
      isRecommended: book.isRecommended,
      isBanner: book.isBanner
    }));

    total.value = data.total;
    currentPage.value = data.current;
  } else {
    allBookData.value = [];
    total.value = 0;
    ElMessage.warning('暂无图书数据');
  }
};


//获取图书列表
const getBookList = async (params = {}) => {
  try {
    const requestParams = {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...params
    };

    const token = sessionStorage.getItem('token');
    const res = await axios.get('/admin/books/list', {
      params: requestParams,
      headers: {
        Authorization: `${token}`
      }
    });

    if (res.data.code === 0 && res.data.data) {
      const data = res.data.data;
      const records = data.records || [];

      tableData.value = records.map((book, index) => ({
        //index: (data.current - 1) * data.size + index + 1,
        bookName: book.title,
        bookIntro: book.description,
        author: book.author,
        publisher: book.publisher,
        isbn: book.isbn,
        relatedCategory: book.categoryId,
        status: book.status === 1 ? '上架' : '下架',
        icon: book.coverUrl?.startsWith('http') 
              ? book.coverUrl 
              : `http://localhost:8080${book.coverUrl}`,
        stock: book.stock,
        price: book.price,
        bookId: book.bookId,
        isRecommended: book.isRecommended,
        isBanner: book.isBanner
      }));

      total.value = data.total;

      // ✅ 只有当不是从修改操作触发时才更新当前页码
      if (!params || !params.page) {
        currentPage.value = data.current;
      }

    } else {
      tableData.value = [];
      total.value = 0;
      ElMessage.warning('暂无图书数据');
    }
  } catch (err) {
    console.error('请求失败:', err);
    ElMessage.error('网络错误，请稍后再试');
  }
};
//获取分类
const getCategoryList = async () => {
  try {
    const token = sessionStorage.getItem('token');
    const res = await axios.get('/categorys/list', 
     {
    headers: {
      Authorization: `${token}` // 添加 Token 到请求头 
    }}
  )
    if (res.data.code === 0) {
      categoryOptions.value = res.data.data.map(cat => ({
        value: cat.categoryId,
        label: cat.categoryName
      }))
    } else {
      ElMessage.error('加载分类失败')
    }
  } catch (err) {
    console.error('请求失败:', err)
    ElMessage.error('网络错误，请稍后再试')
  }
}

const getCategoryLabel = (categoryId) => {
  const category = categoryOptions.value.find(
    (item) => item.value === categoryId
  )
  return category ? category.label : '未知分类'
}

// 重置方法
const resetForm = () => {
   searchForm.value = {
     bookName: '',
     author: '',
     isbn: ''
   };
  getBookList()
};

// 修改方法
// 控制对话框显示隐藏
const editDialogVisible = ref(false)

// 当前编辑的图书对象
const editForm = ref({
  bookId: null,
  bookName: '',
  author: '',
  publisher: '',
  price:'',
  isbn: '',
  status: '',
  bookIntro: '',
  icon: '',
  relatedCategory: '',
  stock:'',
  isRecommended: '',
  isBanner: ''
})

let currentEditIndex = -1 // 当前编辑的行索引

// 打开编辑对话框并填充数据
const handleEdit = (index, row) => {
  console.log('当前行数据:', row);
  currentEditIndex = index
  editForm.value = {
    bookId: row.bookId,
    bookName: row.bookName,
    author: row.author,
    publisher: row.publisher,
    price: Number(row.price).toFixed(2),
    isbn: row.isbn,
    status: row.status,
    bookIntro: row.bookIntro,
    icon: row.icon,
    relatedCategory: row.relatedCategory,
    stock: row.stock,
    isRecommended: row.isRecommended || 1,
    isBanner: row.isBanner || 1
  }
  editDialogVisible.value = true
}

// 修改图书
const submitEditForm = async() => {
  const formData = editForm.value
  const priceStr = String(editForm.value.price).trim();
  const stockStr = String(editForm.value.stock).trim();

  if (!formData.bookName.trim()) {
    ElMessage.warning('图书名称不能为空')
    return
  }

  if (!formData.author.trim()) {
    ElMessage.warning('作者不能为空');
    return;
  }
  if (!formData.publisher.trim()) {
    ElMessage.warning('出版社不能为空');
    return;
  }

  if (!formData.isbn.trim()) {
    ElMessage.warning('ISBN号不能为空')
    return
  }
  if (!/^(978|979)\d{10}$/.test(formData.isbn)) {
    ElMessage.warning('请输入合法的 ISBN 号（978或979开头的13位数字）');
    return;
  }

  if (!priceStr) {
  ElMessage.warning('价格不能为空');
  return;
  }
  // if(!formData.stock.trim()){
  //   ElMessage.warning('库存不能为空')
  //   return
  // }
  //  if (!/^\d+(\.\d{1,2})?$/.test(priceStr)) {
  //    ElMessage.warning('价格请输入最多两位小数的数字');
  //    return;
  //  }

  //  if (!/^\d+$/.test(formData.stock) || Number(formData.stock) < 0) {
  //    ElMessage.warning('库存必须为非负整数');
  //    return;
  //  }
  if (!/^\d+(\.\d{2})$/.test(priceStr)) {
  ElMessage.warning('请输入合法的两位小数格式（例如：10.00 或 5.20）');
  return;
}
  if (!stockStr) {
  ElMessage.warning('库存不能为空');
  return;
}
if (!/^\d+$/.test(stockStr)) {
  ElMessage.warning('库存必须为非负整数');
  return;
}


  let imageUrl = formData.icon; 

  
  if (uploadRef.value?.uploadFiles?.length > 0) {
    try {
      imageUrl = await uploadCoverImage(); // 上传新图
      editForm.value.icon = imageUrl;
    } catch (err) {
      return; // 上传失败则中断
    }
  }

   const bookId = formData.bookId

  const payload = {
    title: formData.bookName,
    description: formData.bookIntro,
    author: formData.author,
    publisher: formData.publisher,
    isbn: formData.isbn,
    categoryId: formData.relatedCategory,
    price: Number(formData.price),
    stock: Number(formData.stock),
    coverUrl: imageUrl,
    isRecommended: formData.isRecommended, 
    isBanner: formData.isBanner
  }

  const token = sessionStorage.getItem('token');
  try {
    const res = await axios.put(`/admin/books/modify/${bookId}`, payload,{
    headers: {
    Authorization: `${token}`
      }
    })

    if (res.data.code === 0) {
      ElMessage.success('图书修改成功')
       await getBookList({
        page: currentPage.value,
        pageSize: pageSize.value
      });
      editDialogVisible.value = false
    } else {
      ElMessage.error(res.data.message || '图书修改失败')
    }
  } catch (error) {
    console.error('修改失败:', error)
    ElMessage.error('网络错误，请稍后再试')
  }
}

//删除图书
const handleDelete = async (index, row) => {
  const bookId = row.bookId;

  try {
    // 弹窗确认是否删除
    const confirmResult = await ElMessageBox.confirm(
      '此操作将永久删除该图书, 是否继续?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    if (confirmResult === 'confirm') {
      const token = sessionStorage.getItem('token');
      // 发送删除请求
      const res = await axios.delete(`/admin/books/delete/${bookId}`,{
    headers: {
    Authorization: `${token}`
      }
    });

      if (res.data.code === 0) {
        ElMessage.success('图书删除成功');
        // 更新表格数据（移除已删除项）
        tableData.value.splice(index, 1);
        // 如果当前页数据为空，就请求上一页的数据
        if (tableData.value.length === 0 && currentPage.value > 1) {
          currentPage.value--; // 回退一页
        }
        // 再次获取当前页数据，确保数据是最新的
        await getBookList({
          page: currentPage.value,
          pageSize: pageSize.value
        });
      } else {
        ElMessage.error(res.data.message || '图书删除失败');
      }
    }
  } catch (error) {
    // 取消删除
    ElMessage.info('已取消删除');
  }
}

//上下架
const toggleStatus = async (index, row) => {
  const newStatus = row.status === '上架' ? '下架' : '上架';
  const bookId = row.bookId;

  try {
    let res;

    const token = sessionStorage.getItem('token');
    if (newStatus === '上架') {
      // 调用上架接口
      res = await axios.put(`/admin/books/publish/${bookId}`, {}, 
  {
    headers: {
      Authorization: `${token}`
    }
  });
    } else {
      // 调用下架接口
      res = await axios.put(`/admin/books/unpublish/${bookId}`, {},
  {
    headers: {
      Authorization: `${token}`
    }
  });
    }

    if (res.data.code === 0) {
      ElMessage.success(`${newStatus}成功`);
      tableData.value[index].status = newStatus;
    } else {
      ElMessage.error(res.data.message || `${newStatus}失败`);
    }
  } catch (error) {
    console.error('切换状态失败:', error);
    ElMessage.error('网络错误，请稍后再试');
  }
}

// 上传前校验
const beforeAvatarUpload = (rawFile) => {
   const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']; 
  if (!validTypes.includes(rawFile.type)) {
    ElMessage.error('只能上传 JPG/PNG/GIF/WEBP 格式的图片!');
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }
  return true;
};
//修改图书封面图
const customUpload = async (options) => {
  const { file } = options;

  try {
    const formData = new FormData();
    formData.append('file', file);

    const token = sessionStorage.getItem('token');
    const res = await axios.post('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: `${token}`
      }
    });

    if (res.data.code === 0) {
      editForm.value.icon = res.data.data; 
    } else {
      ElMessage.error('封面图上传失败');
    }
  } catch (error) {
    console.error('上传错误:', error);
    ElMessage.error('网络错误，请稍后再试');
  }
};
onMounted(() => {
  getBookList()
  getCategoryList()
})
// 监听 currentPage 和 pageSize 的变化
watch([currentPage, pageSize], async () => {
  await getBookList();
});
</script>

<style scoped>
.book-list {
  padding: 20px;
}

.demo-form-inline {
  margin-bottom: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

</style>